<?php

namespace Ycr\Pack\helpers;

use Ycr\Pack\exception\HttpErrorException;

/**
 * Class EncryptionHelper
 * @author ycr <Email: yuncran@126.com>
 */
class EncryptionHelper
{

    /**
     * 创建参数(包括签名的处理)
     * $paramArr = [
     *     'time' => time(),
     *     'nonceStr' => \common\helpers\StringHelper::random(8),
     *     'appId' => 'doormen',
     * ]
     * @param array $paramArr 变量参数
     * @param string $secret 秘钥(appSecret)
     * @param string $signName
     * @return bool|string
     * @author ycr <Email: yuncran@126.com>
     */
    public static function createUrlParam(array $paramArr, $secret, $signName = 'sign')
    {
        $paraStr = "";
        ksort($paramArr);
        foreach ($paramArr as $key => $val) {
            if ($key != '' && $val != '') {
                $paraStr .= $key . '=' . urlencode($val) . '&';
            }
        }
        // 去掉最后一个&
        $paraStr = substr($paraStr, 0, strlen($paraStr) - 1);
        $signStr = $paraStr . $secret;// 排好序的参数加上secret,进行md5
        $sign = strtolower(md5($signStr));
        $paraStr .= '&';
        $paraStr .= $signName . '=' . $sign;// 将md5后的值作为参数,便于服务器的效验

        return $paraStr;
    }


    /**
     * 解密url
     * @param array $paramArr
     * @param $secret
     * @param string $signName
     * @return bool
     * @throws HttpErrorException
     * @author ycr <Email: yuncran@126.com>
     */
    public static function decodeUrlParam(array $paramArr, $secret, $signName = 'sign')
    {
        $sign = $paramArr[$signName];
        unset($paramArr[$signName]);

        ksort($paramArr);
        $signStr = '';
        foreach ($paramArr as $key => $val) {
            $signStr .= $key . '=' . urlencode($val) . '&';
        }
        // 去掉最后一个&
        $signStr = substr($signStr, 0, strlen($signStr) - 1);
        // 排好序的参数加上secret,进行md5
        $signStr .= $secret;
        if (strtolower(md5($signStr)) !== $sign) {
            throw new HttpErrorException('签名错误', 401);
        }
        return true;
    }


}